/**
 * Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 * http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.common.controller;

import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.permission.SPIAccountAnno;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.NotNull;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

@Api(tags = "FileUtil", description = "文件下载接口")
@RestController
@RequestMapping("/fileUtil")
public class FileController {
    private Logger logger = LoggerFactory.getLogger(FileController.class);
    @Value("${breakpoint.upload.dir}")
    private String defaultDir;

    @ApiOperation(value = "下载文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "path", value = "文件地址", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "fileName", value = "文件名称", required = true, paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/{method}.htm", method = {RequestMethod.GET})
    public HttpEntity<?> FileDownload(@NotNull(message = "参数异常") @RequestParam("path") String path, @NotNull(message = "参数异常") @RequestParam("fileName") String fileName, @PathVariable("method") String method) {
        String temp = path.substring(path.lastIndexOf("/") + 1);
        File file = new File(defaultDir, temp);
        String mimeType = "application/octet-stream";
        try {
            mimeType = Files.probeContentType(file.toPath());
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        try (InputStream inStream = new FileInputStream(file);
             ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[inStream.available()];
            int n = 0;
            while (-1 != (n = inStream.read(buffer))) {
                os.write(buffer, 0, n);
            }
            HttpHeaders header = new HttpHeaders();
            String ext = file.getName();
            ext = ext.substring(ext.lastIndexOf(".") + 1);
            String filenameEncode = URLEncoder.encode(fileName + "." + ext, StandardCharsets.UTF_8);
            header.add("Content-Disposition", ("download".equals(method) ? "attachment" : "inline") + "; filename=" + filenameEncode);

            header.add("Content-Type", mimeType);

            return new ResponseEntity<>(os.toByteArray(), header, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(e.toString(), HttpStatus.OK);
        }
    }

    @ApiOperation("获取文件大小")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "path", value = "文件路径", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/getFileSize.htm", method = RequestMethod.POST)
    public MessageBean<Long> detailOperationLog(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = true) final String path) {
        MessageBean<Long> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(10000);
            msg.setDescription("未登录");
            return msg;
        }
        try {
            if (StringUtils.isNotEmpty(path)) {
                String pathStr = path.split("#")[0];
                URL url = new URL(pathStr);
                HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
                //根据响应获取文件大小
                long contentLength = urlcon.getContentLengthLong();
                urlcon.disconnect();
                msg.setData(contentLength);
            }
            msg.setCode(0);
            msg.setDescription("SUCCESS");
            return msg;
        } catch (Exception e) {
            msg.setCode(-1);
            msg.setDescription("FAIL");
            return msg;
        }
    }
}
